<template>
	<view>
		<button type="primary" @tap="zipImag">压缩上传图片</button>
		<image :src="item" v-for="(item,index) in imgList" :key="index"></image>
		<w-compress ref='wCompress' />
	</view>
</template>

<script>
	import WCompress from '@/components/w-compress/w-compress.vue'
	import toBlob from './zip.js'
	import config from '@/utils/config.js'
	export default {
		components: {
			WCompress
		},
		data() {
			return {
				imgList: [],
			}
		},
		methods: {
			//选择图片并压缩	
			zipImag() {
				let _this = this
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['all'],
					success: (res) => {
						uni.showLoading({
							title: '图片压缩中...'
						});
						_this.zip(res.tempFilePaths)
					}
				});
			},
			/**
			 * 压缩
			 * @param {Object} tempFilePaths
			 */
			async zip(tempFilePaths) {
				this.$refs.wCompress.start(tempFilePaths, {
						pixels: 200000, // 最大分辨率，默认二百万
						quality: 0.1, // 压缩质量，默认0.8
						type: 'png', // 图片类型，默认jpg
						base64: true, // 是否返回base64，默认false，非H5有效
					})
					.then(res => {
						uni.hideLoading()
						// this.imgList =res
						console.log(res)
						uni.showLoading({
							title: '图片上传中...'
						});
						this.uploads(res)
					})
					.catch(e => {
						console.log(e)
						uni.hideLoading()
					})
			},
			/**上传
			 * @param {Object} url
			 */
			async up_img(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: config.BaseUrl + '/repair_user?action=UploadFile', //仅为示例，非真实的接口地址
						filePath: url,
						name: 'file[]',
						formData: {},
						success: (uploadFileRes) => {
							resolve(JSON.parse(uploadFileRes.data).result[0].file);
						}
					});
				})
			},
			/**
			 * 批量上传
			 * @param {Object} res base64
			 */
			async uploads(res) {
				let arr = []
				for (let index in res) {
					arr[index] = await this.up_img(this.imgList[index])
				}
				console.log(arr)
				uni.showToast({
					title: `上传成功`,
					icon: 'success'
				});
				this.imgList = res
				return arr;
			},

		}
	}
</script>

<style>
</style>
